<template>
  <div class="container">
    <div class="content-wrapper">
      <!-- 主内容区 -->
      <div class="main-content">
        <!-- <div class="status-bar">
          <div class="current-status">
            <span v-if="isReadOnly">当前状态：查看信息</span>
            <span v-else>当前状态：编辑信息</span>
          </div>
          <div class="loading-overlay" v-if="isLoading">
            <i class="fa fa-spinner fa-spin"></i> 加载中...
          </div>
        </div> -->
        
        <!-- 表单区域 -->
        <div class="form-container">
          <el-tabs v-model="activeTab" @tab-click="handleTabClick">
            <el-tab-pane label="基本信息" name="basicInfo">
              <div class="form-section" id="personal-info">
                <div class="section-header">
                  <h2>个人信息</h2>
                </div>
                
                <div class="personal-info-container">
                  <!-- 照片区域 -->
                  <div class="photo-section" v-for="(field, key) in fieldGroups.basicInfo" :key="key" v-if="key === 'photoUrl'">
                    <template>
                      <div v-if="isReadOnly" class="readonly-value photo-container">
                        <div class="photo-preview" v-if="formData[key]">
                          <img :src="formData[key]" alt="照片预览" :key="Date.now() + '_photo'">
                        </div>
                        <div class="photo-placeholder" v-else>
                          <i class="el-icon-user-solid"></i>
                          <span>未上传照片</span>
                        </div>
                      </div>
                      <div v-else class="editable-value photo-container">
                        <div class="photo-upload-wrapper">
                          <div class="photo-preview" v-if="formData[key]">
                            <img :src="formData[key]" alt="照片预览" :key="Date.now() + '_photo_edit'">
                            <div class="photo-overlay">
                              <i class="el-icon-camera"></i>
                              <span>更换照片</span>
                            </div>
                          </div>
                          <div class="photo-placeholder" v-else>
                            <i class="el-icon-plus"></i>
                            <span>上传照片</span>
                          </div>
                          <input 
                            :type="field.type || 'file'" 
                            :id="key" 
                            :accept="field.accept || 'image/*'" 
                            @change="handleFileUpload(key, $event)"
                            class="photo-input"
                          >
                        </div>
                        <div class="photo-requirements">
                          <div class="requirement-item">
                            <i class="el-icon-info"></i>
                            <span>请上传一寸免冠彩色照片</span>
                          </div>
                          <div class="requirement-item">
                            <i class="el-icon-picture"></i>
                            <span>建议尺寸 413×531 像素</span>
                          </div>
                          <div class="requirement-item">
                            <i class="el-icon-document"></i>
                            <span>文件大小不超过2MB</span>
                          </div>
                        </div>
                        <span class="error-message" v-if="formErrors[key]">{{ formErrors[key] }}</span>
                      </div>
                    </template>
                  </div>

                  <!-- 基本信息表单 -->
                  <div class="form-grid">
                    <div class="form-group" v-for="(field, key) in fieldGroups.basicInfo" :key="key">
                      <template v-if="key !== 'photoUrl'">
                        <label :for="key" class="required">{{ field.label }}</label>
                        <div v-if="isReadOnly" class="readonly-value">
                          <span v-if="!['isWorking', 'gender'].includes(key)">
                            {{ getDisplayValue(key, formData[key]) }}
                          </span>
                          <span v-if="key === 'isWorking'">
                            {{ formData[key] === '是' ? '在职' : '非在职' }}
                          </span>
                          <span v-if="key === 'gender'">
                            {{ formData[key] || '未选择' }}
                          </span>
                        </div>
                        <div v-else class="editable-value">
                          <template v-if="key === 'gender' || key === 'politicalStatus' || key === 'health' || key === 'education' || key === 'professionalTitle' || key === 'isWorking'">
                            <select :id="key" v-model="formData[key]">
                              <option value="">请选择</option>
                              <option v-for="(optionValue, optionLabel) in field.options" :value="optionValue" :key="optionValue">
                                {{ optionLabel }}
                              </option>
                            </select>
                          </template>
                          <template v-else>
                            <input :type="field.type || 'text'" :id="key" v-model="formData[key]" :placeholder="field.placeholder || '请输入'">
                          </template>
                          <span class="error-message" v-if="formErrors[key]">{{ formErrors[key] }}</span>
                        </div>
                      </template>
                    </div>
                  </div>
                </div>
              </div>
              
              <div class="form-section" id="major-info">
                <div class="section-header">
                  <h2>专业</h2>
                </div>
                
                <div class="form-grid">
                  <!-- 专业信息表单内容 -->
                  <div class="form-group" v-for="(field, key) in fieldGroups.majorInfo" :key="key">
                    <label :for="key" class="required">{{ field.label }}</label>
                    <div v-if="isReadOnly" class="readonly-value">
                      <span>{{ getDisplayValue(key, formData[key]) }}</span>
                    </div>
                    <div v-else class="editable-value">
                      <input :type="field.type || 'text'" :id="key" v-model="formData[key]" :placeholder="field.placeholder || '请输入'">
                      <span class="error-message" v-if="formErrors[key]">{{ formErrors[key] }}</span>
                    </div>
                  </div>
                </div>
              </div>
              
              <div class="form-section" id="other-info">
                  <div class="section-header">
                    <h2>其他</h2>
                  </div>  
                  <div class="form-grid">
                    <!-- 其他信息表单内容 -->
                    <div class="form-group" v-for="(field, key) in fieldGroups.otherInfo" :key="key">
                      <label :for="key" class="required">{{ field.label }}</label>
                      <div v-if="isReadOnly" class="readonly-value">
                        <span v-if="key === 'registeredQualification'">
                          {{ formData[key] || '无' }}
                        </span>
                        <span v-else>
                          {{ formData[key] === true ? '是' : '否' }}
                        </span>
                      </div>
                      <div v-else class="editable-value">
                        <template v-if="key === 'registeredQualification'">
                          <div class="input-with-hint">
                            <input :type="field.type" :id="key" v-model="formData[key]" :placeholder="field.placeholder">
                          </div>
                        </template>
                        <template v-else>
                          <div class="radio-group">
                            <label class="radio-label">
                              <input type="radio" :name="key" :value="true" v-model="formData[key]"> 是
                            </label>
                            <label class="radio-label">
                              <input type="radio" :name="key" :value="false" v-model="formData[key]"> 否
                            </label>
                          </div>
                        </template>
                        <span class="error-message" v-if="formErrors[key]">{{ formErrors[key] }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </el-tab-pane>
            
            <el-tab-pane label="工作履历" name="workExperience">
              <div class="form-section" id="work-experience">
                <div class="section-header">
                  <h2>主要工作经历</h2>
                </div> 
                <el-table 
                  :data="row.workExperience || []" 
                  border 
                  style="margin-bottom: 20px;"
                  v-loading="!row.workExperience"
                >
                  <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
                  <el-table-column label="工作单位" prop="workUnit" min-width="150" show-overflow-tooltip>
                    <template slot-scope="scope">
                      {{ scope.row.workUnit || '-' }}
                    </template>
                  </el-table-column>
                  <el-table-column label="开始时间" prop="startTime" width="120" align="center">
                    <template slot-scope="scope">
                      {{ scope.row.startTime || '-' }}
                    </template>
                  </el-table-column>
                  <el-table-column label="结束时间" prop="endTime" width="120" align="center">
                    <template slot-scope="scope">
                      {{ scope.row.endTime === 'null' || !scope.row.endTime ? '至今' : scope.row.endTime }}
                    </template>
                  </el-table-column>
                  <el-table-column label="职称" prop="jobTitle" width="150" align="center" show-overflow-tooltip>
                    <template slot-scope="scope">
                      {{ scope.row.jobTitle || '-' }}
                    </template>
                  </el-table-column>
                  <el-table-column label="职务" prop="jobDuty" min-width="150" show-overflow-tooltip>
                    <template slot-scope="scope">
                      {{ scope.row.jobDuty === '无' ? '-' : (scope.row.jobDuty || '-') }}
                    </template>
                  </el-table-column>
                </el-table>

                <div class="section-header" style="margin-top: 20px;">
                  <h2>社会兼、聘职情况</h2>
                </div> 
                <el-table 
                  :data="row.socialExperience || []" 
                  border 
                  style="margin-bottom: 20px; width: 100%"
                  v-loading="!row.socialExperience"
                  :header-cell-style="{
                    background: '#f5f7fa',
                    color: '#606266',
                    fontWeight: 600,
                    padding: '8px 0'
                  }"
                  :cell-style="{
                    padding: '8px'
                  }"
                >
                  <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
                  <el-table-column 
                    label="兼职单位" 
                    prop="partTimeUnit"
                    min-width="150"
                    show-overflow-tooltip
                  >
                    <template slot-scope="scope">
                      <span class="work-unit">{{ scope.row.partTimeUnit || '-' }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column 
                    label="开始时间" 
                    prop="startTime" 
                    width="100" 
                    align="center"
                  >
                    <template slot-scope="scope">
                      {{ scope.row.startTime || '-' }}
                    </template>
                  </el-table-column>
                  <el-table-column 
                    label="结束时间" 
                    prop="endTime" 
                    width="100" 
                    align="center"
                  >
                    <template slot-scope="scope">
                      {{ scope.row.endTime === 'null' || !scope.row.endTime ? '至今' : scope.row.endTime }}
                    </template>
                  </el-table-column>
                  <el-table-column 
                    label="兼职身份" 
                    prop="role" 
                    min-width="120"
                    show-overflow-tooltip
                  >
                    <template slot-scope="scope">
                      {{ scope.row.role || '-' }}
                    </template>
                  </el-table-column>
                </el-table>

                <div class="section-header" style="margin-top: 20px;">
                  <h2>其他</h2>
                </div> 
                <div class="form-group" v-loading="!row.otherInfo">
                  <label>本人专业领域研究及成果:</label>
                  <el-input 
                    type="textarea" 
                    :rows="4" 
                    :value="row.otherInfo && row.otherInfo.researchAchievements ? row.otherInfo.researchAchievements : ''"
                    disabled
                    resize="none"
                    :placeholder="row.otherInfo ? '-' : '加载中...'"
                    class="other-info-textarea"
                  ></el-input>
                </div>
                <div class="form-group" style="margin-top: 16px;">
                  <label>本人参加过何种项目咨询、审查、论证等事项:</label>
                  <el-input 
                    type="textarea" 
                    :rows="4" 
                    :value="row.otherInfo && row.otherInfo.projectMatters ? row.otherInfo.projectMatters : ''"
                    disabled
                    resize="none"
                    :placeholder="row.otherInfo ? '-' : '加载中...'"
                    class="other-info-textarea"
                  ></el-input>
                </div>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="附件下载" name="attachmentUpload">
              <div class="form-section" id="attachment-upload">
                <div class="section-header">
                  <h2>附件上传</h2>
                </div>
                <div class="attachments-container">
                  <div class="attachment-item" v-for="(field, key) in fieldGroups.attachmentUpload" :key="key">
                    <div class="attachment-label">
                      <label :for="key" class="required">{{ field.label }}</label>
                    </div>
                    
                    <div v-if="isReadOnly" class="readonly-attachment">
                      <div class="attachment-card" v-if="attachmentFiles[getAttachmentType(key)].fileId" @click="downloadFile(getAttachmentType(key))">
                        <div class="attachment-icon">
                          <i :class="getFileIcon(attachmentFiles[getAttachmentType(key)].fileName)"></i>
                        </div>
                        <div class="attachment-info">
                          <span class="attachment-name">
                            <template v-if="key === 'idCardFrontUrl'">
                              {{ formData.name || '未知专家' }}的身份证
                            </template>
                            <template v-else-if="key === 'idCardBackUrl'">
                              {{ formData.name || '未知专家' }}的最高学历(学位)证书及技术职称
                            </template>
                            <template v-else-if="key === 'degreeCertificateUrl'">
                              {{ formData.name || '未知专家' }}的职业资格证书
                            </template>
                            <template v-else-if="key === 'professionalCertificateUrl'">
                              {{ formData.name || '未知专家' }}的研究成果及工作成就材料
                            </template>
                            <template v-else-if="key === 'otherDocumentsUrl'">
                              {{ formData.name || '未知专家' }}的专家入库申请表
                            </template>
                            <template v-else>
                              {{ attachmentFiles[getAttachmentType(key)].fileName }}
                            </template>
                          </span>
                          <span class="attachment-action">
                            <i class="el-icon-download"></i>
                            点击下载
                          </span>
                        </div>
                      </div>
                      <div class="attachment-empty" v-else>
                        <i class="el-icon-document"></i>
                        <span>
                          <template v-if="key === 'idCardFrontUrl'">
                            {{ formData.name || '未知专家' }}的身份证未上传
                          </template>
                          <template v-else-if="key === 'idCardBackUrl'">
                            {{ formData.name || '未知专家' }}的最高学历(学位)证书及技术职称未上传
                          </template>
                          <template v-else-if="key === 'degreeCertificateUrl'">
                            {{ formData.name || '未知专家' }}的职业资格证书未上传
                          </template>
                          <template v-else-if="key === 'professionalCertificateUrl'">
                            {{ formData.name || '未知专家' }}的研究成果及工作成就材料未上传
                          </template>
                          <template v-else-if="key === 'otherDocumentsUrl'">
                            {{ formData.name || '未知专家' }}的专家入库申请表未上传
                          </template>
                          <template v-else>
                            {{ attachmentFiles[getAttachmentType(key)].fileName }}
                          </template>
                        </span>
                      </div>
                    </div>
                    
                    <div v-else class="editable-attachment">
                      <div class="attachment-card" v-if="attachmentFiles[getAttachmentType(key)].fileId">
                        <div class="attachment-icon">
                          <i :class="getFileIcon(attachmentFiles[getAttachmentType(key)].fileName)"></i>
                        </div>
                        <div class="attachment-info">
                          <span class="attachment-name">
                            <template v-if="key === 'idCardFrontUrl'">
                              {{ formData.name || '未知专家' }}的身份证
                            </template>
                            <template v-else-if="key === 'idCardBackUrl'">
                              {{ formData.name || '未知专家' }}的最高学历(学位)证书及技术职称
                            </template>
                            <template v-else-if="key === 'degreeCertificateUrl'">
                              {{ formData.name || '未知专家' }}的职业资格证书
                            </template>
                            <template v-else-if="key === 'professionalCertificateUrl'">
                              {{ formData.name || '未知专家' }}的研究成果及工作成就材料
                            </template>
                            <template v-else-if="key === 'otherDocumentsUrl'">
                              {{ formData.name || '未知专家' }}的专家入库申请表
                            </template>
                            <template v-else>
                              {{ attachmentFiles[getAttachmentType(key)].fileName }}
                            </template>
                          </span>
                          <div class="attachment-actions">
                            <span class="action-download" @click.stop="downloadFile(getAttachmentType(key))">
                              <i class="el-icon-download"></i>
                              下载
                            </span>
                            <span class="action-delete" @click.stop="deleteFile(getAttachmentType(key))">
                              <i class="el-icon-delete"></i>
                              删除
                            </span>
                          </div>
                        </div>
                      </div>
                      
                      <div class="attachment-upload" v-else>
                        <input 
                          :type="field.type || 'file'" 
                          :id="key" 
                          :accept="field.accept || 'image/*'" 
                          @change="handleFileUpload(getAttachmentType(key), $event)"
                          class="attachment-input"
                        >
                        <div class="upload-area">
                          <i class="el-icon-upload"></i>
                          <div class="upload-text">
                            <span>点击上传或拖拽文件到此处</span>
                            <p class="upload-tip">支持 PDF、PNG、JPG 格式，文件大小不超过10MB</p>
                          </div>
                        </div>
                      </div>
                      <span class="error-message" v-if="formErrors[key]">{{ formErrors[key] }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </el-tab-pane>
            
            <!-- 信息审核页面 -->
            <!-- <el-tab-pane label="信息审核" name="informationReview">
              <div class="form-section" id="information-review">
                <div class="section-header">
                  <h2>信息审核</h2> 
                </div> 
                <div class="section-content">
                  <el-input
                    type="textarea"
                    :rows="15"
                    disabled
                    style="height: 300px" 
                  ></el-input>
                </div>                             
              </div>
            </el-tab-pane> -->
          </el-tabs>
        </div>
      </div>
    </div>

    <!-- 文件预览弹窗 -->
    <el-dialog
      :visible.sync="previewDialogVisible"
      :title="previewFileName"
      width="70%"
      class="preview-dialog"
      @close="closePreview"
    >
      <div class="preview-container">
        <!-- PDF预览 -->
        <iframe
          v-if="isPdfFile"
          :src="previewUrl"
          class="pdf-preview"
        ></iframe>
        <!-- 图片预览 -->
        <img
          v-else-if="isImageFile"
          :src="previewUrl"
          class="image-preview"
          alt="预览图片"
        >
        <!-- 不支持的文件格式 -->
        <div v-else class="unsupported-preview">
          <i class="el-icon-warning"></i>
          <p>该文件格式暂不支持预览</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getExpertAttach, getFileInfo, downloadFile} from '@/api/table'
// import role from '../../api/system/role';
export default {
  name: 'ExpertShow',
  props: {
    row: {
      type: Object,
      required: true,
      default: () => ({})
    }
  },
  data() {
    return {
      activeTab: 'basicInfo',
      isReadOnly: true,
      isLoading: false,
      isAdding: false,
      formData: {
        // 基本信息
        photoUrl: '',
        name: '',
        gender: '',
        ethnicity: '',
        birthDate: '',
        idCard: '',
        nativePlace: '',
        politicalStatus: '',
        healthStatus: '',
        education: '',
        graduateSchool: '',
        workUnit: '',
        job: '',
        title: '',
        isPublicOfficial: false,
        phone: '',
        email: '',
        bankName: '',
        bankAccount: '',
        primaryMajor: '',
        secondMajor: '',
        thirdMajor: '',
        fourthMajor: '',
        fifthMajor: '',
        workTime: '',
        isAcademic: false,
        isDesignMaster: false,
        isSubsidy: false,
        isSpecial: false,
        registeredQualification: '无',
        auditStatus: '',
        auditOpinion: '',
        changeCounts: 0,
        joinMeeting: 0
      },
      workExperienceList: [],
      socialExperienceList: [],
      researchAchievements: '',
      projectMatters: '',
      editingIndex: -1,
      formErrors: {},
      databaseValue: '', // 信息审核页显示的内容
      // 表单字段配置
      fieldGroups: {
        basicInfo: {
          photoUrl: { label: '照片', type: 'file', accept: 'image/*' },
          name: { label: '姓名', type: 'text' },
          gender: { label: '性别', type: 'select', options: { '男': '男', '女': '女' } },
          ethnicity: { label: '民族', type: 'text' },
          birthDate: { label: '出生年月', type: 'date' },
          idCard: { label: '身份证号', type: 'text' },
          nativePlace: { label: '籍贯', type: 'text' },
          politicalStatus: { label: '政治面貌', type: 'text' },
          healthStatus: { label: '健康状况', type: 'text' },
          education: { label: '学历', type: 'text' },
          graduateSchool: { label: '毕业院校', type: 'text' },
          workUnit: { label: '工作单位', type: 'text' },
          job: { label: '职务', type: 'text' },
          title: { label: '职称', type: 'text' },
          isPublicOfficial: { label: '是否为在职人员', type: 'boolean' },
          phone: { label: '手机', type: 'text' },
          email: { label: '邮箱', type: 'email' },
          bankName: { label: '银行名称', type: 'text' },
          bankAccount: { label: '银行卡号', type: 'text' }
        },
        majorInfo: {
          primaryMajor: { label: '第一专业（主专业）', type: 'text' },
          secondMajor: { label: '第二专业', type: 'text' },
          thirdMajor: { label: '第三专业', type: 'text' },
          fourthMajor: { label: '第四专业', type: 'text' },
          fifthMajor: { label: '第五专业', type: 'text' },
          workTime: { label: '从事水利相关领域工作时间', type: 'number' }
        },
        otherInfo: {
          isAcademic: { label: '是否为院士', type: 'radio', options: { '是': '是', '否': '否' } },
          isDesignMaster: { label: '是否为全国或省级工程勘察设计大师（水利）', type: 'radio', options: { '是': '是', '否': '否' } },
          isSubsidy: { label: '是否为享受国务院政府特殊津贴的专家', type: 'radio', options: { '是': '是', '否': '否' } },
          isSpecial: { label: '是否为人才紧缺的特殊专业、特殊领域技术人才', type: 'radio', options: { '是': '是', '否': '否' } },
          registeredQualification: { label: '国家注册执业资格', type: 'text', placeholder: '请输入国家注册执业资格' }
        },
        workExperience: {
          workUnit: { label: '工作单位', type: 'text', placeholder: '请输入工作单位' },
          startTime: { label: '开始时间', type: 'date' },
          endTime: { label: '结束时间', type: 'date' },
          jobTitle: { label: '职称', type: 'text', placeholder: '请输入职称' },
          jobDuty: { label: '职务', type: 'text', placeholder: '请输入职务' },
          jobDescription: { label: '工作描述', type: 'text', placeholder: '请描述您的工作职责和成就' }
        },
        attachmentUpload: {
          idCardFrontUrl: { label: '身份证', type: 'file', accept: 'image/*' },
          idCardBackUrl: { label: '最高学历(学位)证书及技术职称', type: 'file', accept: 'image/*' },
          degreeCertificateUrl: { label: '职业资格', type: 'file', accept: 'image/*' },
          professionalCertificateUrl: { label: '个人研究成果、工作成就、参与评审项目等相关证明查看案例材料', type: 'file', accept: 'image/*' },
          otherDocumentsUrl: { label: '陕西省水利厅专家入库申请表(签字盖章)', type: 'file', accept: 'image/*' }
        }
      },
      formRules: {
        // 表单验证规则
        name: { required: true },
        gender: { required: true },
        ethnicity: { required: true },
        birthDate: { required: true },
        idCard: { required: true, pattern: /(^\d{18}$)|(^\d{17}(\d|X|x)$)/ },
        nativePlace: { required: true },
        politicalStatus: { required: true },
        healthStatus: { required: true },
        education: { required: true },
        graduateSchool: { required: true },
        workUnit: { required: true },
        job: { required: true },
        title: { required: true },
        isPublicOfficial: { required: true },
        phone: { required: true, pattern: /^1[3-9]\d{9}$/ },
        email: { required: true, pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/ },
        workTime: { required: true, min: 0 },
        bankName: { required: true },
        bankAccount: { required: true, pattern: /^\d{16,19}$/ },
        primaryMajor: { required: true },
        secondMajor: { required: true },
        thirdMajor: { required: true },
        fourthMajor: { required: true },
        fifthMajor: { required: true },
        qualification: { required: true },
        isAcademician: { required: true },
        isDesignMaster: { required: true },
        isSpecialExpert: { required: true },
        isSpecialTalent: { required: true },
        // 工作履历验证规则
        workUnit: { required: true },
        startTime: { required: true },
        endTime: { required: true },
        jobTitle: { required: true },
        jobDuty: { required: true },
        jobDescription: { required: true },
        // 附件上传验证规则
        idCardFrontUrl: { required: true },
        idCardBackUrl: { required: true },
        degreeCertificateUrl: { required: true },
        professionalCertificateUrl: { required: true }
      },
      previewDialogVisible: false,
      previewUrl: '',
      previewFileName: '',
      expertId: null,
      isFromDashboard: false,
      attachInfo: null, // 存储附件信息
      attachmentFiles: {
        idCard: { fileId: null, fileName: '未上传文件', address: null },
        certificate: { fileId: null, fileName: '未上传文件', address: null },
        qualification: { fileId: null, fileName: '未上传文件', address: null },
        supportMater: { fileId: null, fileName: '未上传文件', address: null },
        applicationForm: { fileId: null, fileName: '未上传文件', address: null }
      },
      hasLoadedAttachments: false, // 添加标记，避免重复加载
    }
  },
  watch: {
    row: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          // 每次切换专家时，重置为基本信息标签页
          this.activeTab = 'basicInfo';
          
          // 先加载表格数据
          this.loadTableData(newVal);
          
          // 先加载图片数据 - 确保每次切换专家时都会重新加载
          this.loadPhotoData(newVal);
          
          // 然后加载附件信息(只在第一次或id变更时加载)
          const expertId = newVal.expertId || newVal.id;
          if (expertId && (!this.hasLoadedAttachments || expertId !== this.expertId)) {
            this.expertId = expertId;
            // 只有当当前是附件标签页时才立即加载附件
            if (this.activeTab === 'attachmentUpload') {
              this.getAttachInfo(expertId).catch(error => {
                console.error('加载附件失败:', error);
              });
            } else {
              // 否则重置附件加载状态，等待用户切换到附件标签页时再加载
              this.hasLoadedAttachments = false;
            }
          }
        }
      }
    }
  },
  async created() {
    // 初始化标签页为基本信息
    this.activeTab = 'basicInfo';
    
    // 从路由获取专家ID
    const { id } = this.$route.query;
    if (id && !this.hasLoadedAttachments) {
      console.log('从路由获取专家ID:', id);
      this.expertId = id;
      this.isFromDashboard = true;
      this.isReadOnly = true;
      await this.getAttachInfo(id);
      this.hasLoadedAttachments = true; // 标记已经加载过附件
    }
  },
  mounted() {
    console.log('当前专家信息:', this.row);
    if (this.row) {
      this.initializeFormData(this.row);
    }
  },
  computed: {
    isAdding() {
      return this.editingIndex === -1 && !this.isReadOnly;
    },
    isPdfFile() {
      return this.previewUrl.toLowerCase().endsWith('.pdf');
    },
    isImageFile() {
      const ext = this.previewUrl.toLowerCase();
      return ext.endsWith('.png') || ext.endsWith('.jpg') || ext.endsWith('.jpeg');
    }
  },
  methods: {
    // 加载表格数据的方法
    loadTableData(data) {
      console.log('加载专家表格数据:', data ? data.name : '无数据');
      
      if (!data) {
        console.warn('未提供专家数据');
        return;
      }
      
      // 将后端字段名转换为前端字段名
      const mappedData = {
        name: data.name,
        gender: data.gender,
        ethnicity: data.ethnicity,
        birthDate: data.birthDate,
        idCard: data.idCard,
        nativePlace: data.nativePlace,
        politicalStatus: data.politicalStatus,
        healthStatus: data.healthStatus,
        education: data.education,
        graduateSchool: data.graduateSchool,
        workUnit: data.workUnit,
        job: data.job,
        title: data.title,
        isPublicOfficial: data.isPublicOfficial === 1,
        phone: data.phone,
        email: data.email,
        bankName: data.bankName,
        bankAccount: data.bankAccount,
        primaryMajor: data.primaryMajor || '',
        secondMajor: data.secondMajor || '',
        thirdMajor: data.thirdMajor || '',
        fourthMajor: data.fourthMajor || '',
        fifthMajor: data.fifthMajor || '',
        workTime: data.workTime || 0,
        isAcademic: Boolean(data.isAcademic),
        isDesignMaster: Boolean(data.isDesignMaster),
        isSubsidy: Boolean(data.isSubsidy),
        isSpecial: Boolean(data.isSpecial),
        registeredQualification: data.registeredQualification || '无',
        auditStatus: data.auditStatus || '',
        auditOpinion: data.auditOpinion || '',
        changeCounts: data.changeCounts || 0,
        joinMeeting: data.joinMeeting || 0,
        belong: data.belong || '',
        fillStatus: data.fillStatus || 0,
        age: data.age || 0,
        createTime: data.createTime || '',
        updateTime: data.updateTime || '',
        matchedExpertise: data.matchedExpertise || null
      };
      
      // 重置表单数据（先清空photoUrl避免旧照片残留）
      this.formData = {
        photoUrl: '',  // 清空照片，将由loadPhotoData单独处理
        ...mappedData
      };
    },

    // 加载图片数据的方法
    async loadPhotoData(data) {
      console.log('加载专家照片数据:', data ? data.name : '无数据');
      
      // 如果没有photoUrl，先清空当前显示的图片
      if (!data || !data.photoUrl) {
        console.log('专家无照片数据，清空显示');
        this.formData.photoUrl = '';
        return;
      }
      
      try {
        // 检查是否已经是完整的 URL 或 data URL
        if (data.photoUrl.startsWith('http') || data.photoUrl.startsWith('data:image')) {
          console.log('照片已是完整URL或data URL格式');
          this.formData.photoUrl = data.photoUrl;
          
          // 确保图片完全加载
          if (data.photoUrl.startsWith('http')) {
            this.preloadImage(data.photoUrl);
          }
        } else {
          // 如果是 base64 字符串，转换为 data URL
          console.log('照片是base64格式，进行转换');
          const maxLength = 1024 * 1024; // 1MB
          if (data.photoUrl.length > maxLength) {
            console.warn('图片数据过大，可能影响性能');
          }
          
          const dataUrl = `data:image/jpeg;base64,${data.photoUrl}`;
          this.formData.photoUrl = dataUrl;
          
          // 确保图片完全加载
          this.preloadImage(dataUrl);
        }
      } catch (error) {
        console.error('处理图片数据失败:', error);
        this.formData.photoUrl = '';
      }
    },
    
    // 预加载图片确保渲染
    preloadImage(src) {
      return new Promise((resolve, reject) => {
        const img = new Image();
        img.onload = () => {
          console.log('图片预加载成功:', src.substring(0, 30) + '...');
          resolve();
        };
        img.onerror = (err) => {
          console.error('图片加载失败:', err);
          reject(err);
        };
        img.src = src;
      });
    },
    
    // 加载专家数据
    async loadExpertData() {
      this.isLoading = true;
      try {
        // 从 localStorage 获取专家数据
        const expertData = JSON.parse(localStorage.getItem('currentExpertData'));
        if (expertData) {
          // 清除 localStorage 中的数据
          localStorage.removeItem('currentExpertData');
          
          // 如果需要获取更详细的数据，可以调用API
          const detailedData = await this.fetchExpertDetail(expertData.id);
          this.initializeFormData(detailedData || expertData);
          
          // 信息审核页的内容
          this.generateReviewContent();
        } else {
          this.$message.error('未找到专家数据');
          this.$router.push('/dashboard');
        }
      } catch (error) {
        console.error('加载专家数据失败:', error);
        this.$message.error('加载专家信息失败，请重试');
      } finally {
        this.isLoading = false;
      }
    },
    
    // 加载新专家表单
    async loadNewExpertForm() {
      this.isLoading = true;
      try {
        const response = await this.fetchUserData();
        this.initializeFormData(response);
        this.generateReviewContent();
      } catch (error) {
        console.error('获取用户数据失败:', error);
        // this.$message.error('加载个人信息失败，请稍后重试');
      } finally {
        this.isLoading = false;
      }
    },
    
    // 获取专家详细信息
    async fetchExpertDetail(expertId) {
      try {
        // 这里替换为实际的API调用
        const response = await new Promise(resolve => {
          setTimeout(() => {
            resolve({
              // 模拟更详细的专家数据
              id: expertId,
              user_name: "张三",
              gender: "男",
              ethnicity: "汉",
              birth_date: "1990-01-01",
              id_card: "110101199001011234",
              native_place: "北京市",
              political_status: "中共党员",
              health_status: "良好",
              education_level: "本科",
              graduated_school: "清华大学",
              current_work_unit: "水利部",
              current_duty: "工程师",
              professional_title: "中级",
              is_working: "是",
              phone_number: "13800138000",
              email: "zhangsan@example.com",
              working_years: 5,
              photoUrl: "https://picsum.photos/200/300",
              bank_name: "中国工商银行",
              bank_card_number: "6222021101011234567",
              major1: "水利工程",
              major2: "土木工程",
              major3: "",
              major4: "",
              major5: "",
              qualification: "注册土木工程师（水利水电工程）",
              is_academician: "否",
              is_design_master: "否",
              is_special_expert: "否",
              is_special_talent: "否",
              work_experience: [
                {
                  work_unit: "水利部",
                  start_time: "2020-01-01",
                  end_time: "至今",
                  job_title: "工程师",
                  job_duty: "项目负责人",
                  job_description: "负责水利工程项目的规划与实施"
                }
              ],
              social_experience: [
                {
                  partTimeUnit: "中国水利学会",
                  startTime: "2021-03-01",
                  endTime: "至今",
                  role: "会员"
                }
              ],
              research_achievements: "主持完成国家重点研发计划项目1项，发表SCI论文5篇",
              project_matters: "参与南水北调工程可行性研究论证等国家级项目",
              id_card_front_url: "https://example.com/id_card_front.jpg",
              id_card_back_url: "https://example.com/id_card_back.jpg",
              degree_certificate_url: "https://example.com/degree.jpg",
              professional_certificate_url: "https://example.com/cert.jpg",
              other_documents_url: "https://example.com/other.pdf"
            });
          }, 1000);
        });
        return response;
      } catch (error) {
        console.error('获取专家详细信息失败:', error);
        return null;
      }
    },
    
    // 初始化表单数据
    initializeFormData(apiData) {
      // 基本信息映射
      console.log(apiData);
      this.formData.name = apiData.name || '';
      this.formData.gender = apiData.gender || '';
      this.formData.nation = apiData.ethnicity || '';
      this.formData.birthDate = apiData.birth_date || '';
      this.formData.idCard = apiData.id_card || '';
      this.formData.nativePlace = apiData.native_place || '';
      this.formData.politicalStatus = apiData.political_status || '';
      this.formData.healthStatus = apiData.health_status || '';
      this.formData.education = apiData.education_level || '';
      this.formData.graduateSchool = apiData.graduated_school || '';
      this.formData.workUnit = apiData.current_work_unit || '';
      this.formData.job = apiData.current_duty || '';
      this.formData.title = apiData.professional_title || '';
      this.formData.isPublicOfficial = apiData.is_working === '是';
      this.formData.phone = apiData.phone_number || '';
      this.formData.email = apiData.email || '';
      this.formData.workTime = apiData.working_years || null;
      // 修改 photoUrl 的处理逻辑
      if (apiData.photoUrl) {
        // 检查是否已经是完整的 URL 或 data URL
        if (apiData.photoUrl.startsWith('http') || apiData.photoUrl.startsWith('data:image')) {
          this.formData.photoUrl = apiData.photoUrl;
        } else {
          // 如果是 base64 字符串，转换为 data URL
          try {
            // 限制图片大小，如果 base64 字符串太长，可能需要分块处理
            const maxLength = 1024 * 1024; // 1MB
            if (apiData.photoUrl.length > maxLength) {
              console.warn('图片数据过大，可能影响性能');
            }
            this.formData.photoUrl = `data:image/jpeg;base64,${apiData.photoUrl}`;
          } catch (error) {
            console.error('处理图片数据失败:', error);
            this.formData.photoUrl = '';
          }
        }
      } else {
        this.formData.photoUrl = '';
      }
      this.formData.bankName = apiData.bank_name || '';
      this.formData.bankAccount = apiData.bank_card_number || '';
      
      // 专业信息映射
      this.formData.primaryMajor = apiData.major1 || '';
      this.formData.secondMajor = apiData.major2 || '';
      this.formData.thirdMajor = apiData.major3 || '';
      this.formData.fourthMajor = apiData.major4 || '';
      this.formData.fifthMajor = apiData.major5 || '';
      
      // 其他信息映射
      this.formData.qualification = apiData.qualification || '';
      this.formData.isAcademic = apiData.is_academician === '是' ? '是' : '否';
      this.formData.isDesignMaster = apiData.is_design_master === '是' ? '是' : '否';
      this.formData.isSubsidy = apiData.is_special_expert === '是' ? '是' : '否';
      this.formData.isSpecial = apiData.is_special_talent === '是' ? '是' : '否';
      
      // 工作履历映射
      this.workExperienceList = apiData.work_experience.map(exp => ({
        workUnit: exp.work_unit,
        startTime: exp.start_time,
        endTime: exp.end_time,
        jobTitle: exp.job_title,
        jobDuty: exp.job_duty,
        jobDescription: exp.job_description
      }));
      
      // 社会兼、聘职情况映射
      this.socialExperienceList = apiData.social_experience.map(exp => ({
        partTimeUnit: exp.partTimeUnit,
        startTime: exp.startTime,
        endTime: exp.endTime,
        role: exp.role,
        id: exp.id,
        expertId: exp.expertId
      })) || [];
      
      // 其他信息映射
      this.researchAchievements = apiData.research_achievements || '';
      this.projectMatters = apiData.project_matters || '';
      
      // 附件上传映射
      this.formData.idCardFrontUrl = apiData.id_card_front_url || '';
      this.formData.idCardBackUrl = apiData.id_card_back_url || '';
      this.formData.degreeCertificateUrl = apiData.degree_certificate_url || '';
      this.formData.professionalCertificateUrl = apiData.professional_certificate_url || '';
      this.formData.otherDocumentsUrl = apiData.other_documents_url || '';
      
      // 保存初始数据用于撤销修改
      this.initialData = JSON.parse(JSON.stringify(this.formData));
      this.initialWorkExperience = [...this.workExperienceList];
      this.initialSocialExperience = [...this.socialExperienceList];
      this.initialResearchAchievements = this.researchAchievements;
      this.initialProjectMatters = this.projectMatters;
      this.generateReviewContent()
    },
    
    // 信息审核页的内容
    generateReviewContent() {
      let content = "个人信息审核表\n\n";
      
      // 添加基本信息
      content += "一、基本信息\n";
      content += `姓名：${this.formData.name || '未填写'}\n`;
      content += `性别：${this.formData.gender || '未填写'}\n`;
      content += `民族：${this.formData.nation || '未填写'}\n`;
      content += `出生年月：${this.formData.birthDate || '未填写'}\n`;
      content += `身份证号：${this.formData.idCard || '未填写'}\n`;
      content += `政治面貌：${this.getDisplayValue('politicalStatus', this.formData.politicalStatus)}\n`;
      content += `学历：${this.getDisplayValue('education', this.formData.education)}\n`;
      content += `毕业院校：${this.formData.graduateSchool || '未填写'}\n`;
      content += `工作单位：${this.formData.workUnit || '未填写'}\n`;
      content += `职称：${this.getDisplayValue('title', this.formData.title)}\n`;
      content += `手机号：${this.formData.phone || '未填写'}\n\n`;
      
      // 添加专业信息
      content += "二、专业信息\n";
      content += `第一专业：${this.formData.primaryMajor || '未填写'}\n`;
      content += `第二专业：${this.formData.secondMajor || '未填写'}\n`;
      content += `第三专业：${this.formData.thirdMajor || '未填写'}\n\n`;
      
      // 添加工作履历
      content += "三、工作履历\n";
      this.workExperienceList.forEach((exp, index) => {
        content += `工作经历 ${index + 1}：\n`;
        content += `  单位：${exp.workUnit || '未填写'}\n`;
        content += `  时间：${exp.startTime || '未填写'} 至 ${exp.endTime || '未填写'}\n`;
        content += `  职称：${exp.jobTitle || '未填写'}\n`;
        content += `  职务：${exp.jobDuty || '未填写'}\n`;
        content += `  描述：${exp.jobDescription || '未填写'}\n\n`;
      });
      
      // 添加社会兼、聘职情况
      content += "四、社会兼、聘职情况\n";
      this.socialExperienceList.forEach((exp, index) => {
        content += `兼职经历 ${index + 1}：\n`;
        content += `  单位：${exp.partTimeUnit || '未填写'}\n`;
        content += `  时间：${exp.startTime || '未填写'} 至 ${exp.endTime || '未填写'}\n`;
        content += `  身份：${exp.role || '未填写'}\n\n`;
      });
      
      // 添加其他信息
      content += "五、其他信息\n";
      content += `专业领域研究及成果：${this.researchAchievements || '未填写'}\n\n`;
      content += `参与项目咨询、审查、论证等事项：${this.projectMatters || '未填写'}\n\n`;
      
      // 添加附件信息
      content += "六、附件上传\n";
      content += `身份证：${this.formData.idCardFrontUrl ? '已上传' : '未上传'}\n`;
      content += `学历证书：${this.formData.degreeCertificateUrl ? '已上传' : '未上传'}\n`;
      content += `职业资格：${this.formData.professionalCertificateUrl ? '已上传' : '未上传'}\n`;
      
      this.databaseValue = content;
    },
    
    // 切换编辑/查看模式
    toggleEditMode() {
      this.isReadOnly = !this.isReadOnly;
      
      if (!this.isReadOnly) {
        // 进入编辑模式时，复制一份数据用于撤销
        this.tempData = JSON.parse(JSON.stringify(this.formData));
        this.tempWorkExperience = [...this.workExperienceList];
        this.tempSocialExperience = [...this.socialExperienceList];
        this.tempResearchAchievements = this.researchAchievements;
        this.tempProjectMatters = this.projectMatters;
      } else {
        // 退出编辑模式时，清空临时数据
        this.tempData = null;
        this.tempWorkExperience = null;
        this.tempSocialExperience = null;
        this.tempResearchAchievements = null;
        this.tempProjectMatters = null;
      }
    },
    
    // 保存表单
    async saveForm() {
      // 表单验证
      if (!this.validateForm()) {
        return;
      }
      
      this.isLoading = true;
      
      try {
        // 模拟API请求，实际项目中需替换为真实接口
        await this.submitFormData();
        
        // 信息审核页内容
        this.generateReviewContent();
        
        // 保存成功提示
        this.$message.success('保存成功');
        
        // 切换回查看模式
        this.isReadOnly = true;
        
        // 更新初始数据
        this.initialData = JSON.parse(JSON.stringify(this.formData));
        this.initialWorkExperience = [...this.workExperienceList];
        this.initialSocialExperience = [...this.socialExperienceList];
        this.initialResearchAchievements = this.researchAchievements;
        this.initialProjectMatters = this.projectMatters;
      } catch (error) {
        console.error('保存失败:', error);
        this.$message.error('保存失败，请稍后重试');
      } finally {
        this.isLoading = false;
      }
    },
    
    // 撤销修改
    cancelEdit() {
      // 恢复初始数据
      this.formData = JSON.parse(JSON.stringify(this.initialData));
      this.workExperienceList = [...this.initialWorkExperience];
      this.socialExperienceList = [...this.initialSocialExperience];
      this.researchAchievements = this.initialResearchAchievements;
      this.projectMatters = this.initialProjectMatters;
      
      // 切换回查看模式
      this.isReadOnly = true;
    },
    
    // 表单验证
    validateForm() {
      this.formErrors = {};
      let isValid = true;
      
      // 验证基本信息
      for (const [field, rules] of Object.entries(this.formRules)) {
        if (rules.required && !this.formData[field]) {
          this.formErrors[field] = '此字段为必填项';
          isValid = false;
        }
        
        if (rules.pattern && this.formData[field] && !new RegExp(rules.pattern).test(this.formData[field])) {
          this.formErrors[field] = '格式不正确';
          isValid = false;
        }
        
        if (rules.min !== undefined && this.formData[field] !== null && this.formData[field] < rules.min) {
          this.formErrors[field] = `最小值为${rules.min}`;
          isValid = false;
        }
      }
      
      // 验证工作履历
      if (this.workExperienceList.length === 0) {
        this.formErrors.workExperience = '至少需要添加一条工作经历';
        isValid = false;
      } else {
        // 验证每条工作履历
        for (let i = 0; i < this.workExperienceList.length; i++) {
          const experience = this.workExperienceList[i];
          for (const [field, rules] of Object.entries(this.formRules)) {
            if (rules.required && !experience[field]) {
              this.formErrors[`workExperience_${i}_${field}`] = '此字段为必填项';
              isValid = false;
            }
          }
        }
      }
      
      // 验证附件上传
      for (const field of ['idCardFrontUrl', 'idCardBackUrl', 'degreeCertificateUrl', 'professionalCertificateUrl']) {
        if (!this.formData[field]) {
          this.formErrors[field] = '此字段为必填项';
          isValid = false;
        }
      }
      
      return isValid;
    },
    
    // 处理文件上传
    handleFileUpload(field, event) {
      const file = event.target.files[0];
      if (!file) return;
      
      // 检查文件大小（10MB）
      if (file.size > 10 * 1024 * 1024) {
        this.formErrors[field] = '文件大小不能超过10MB';
        return;
      }
      
      // 检查文件类型
      const allowedTypes = ['application/pdf', 'image/png', 'image/jpeg'];
      if (!allowedTypes.includes(file.type)) {
        this.formErrors[field] = '请上传PDF或图片文件';
        return;
      }
      
      this.formErrors[field] = '';
      
      // 读取文件并预览
      const reader = new FileReader();
      reader.onload = (e) => {
        this.formData[field] = e.target.result;
      };
      reader.readAsDataURL(file);
    },
    
    // 获取选项的显示值
    getDisplayValue(field, value) {
      if (value === null || value === undefined) return '未填写'
      if (typeof value === 'boolean') return value ? '是' : '否'
      return value
    },
    
    // 模拟提交表单数据到API
    async submitFormData() {
      // 实际项目中替换为真实API调用
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve({ success: true });
        }, 1000);
      });
    },
    
    // 切换标签页
    handleTabClick(tab) {
      this.activeTab = tab.name;
      
      // 当用户切换到附件标签页时，按需加载附件信息
      if (tab.name === 'attachmentUpload' && this.expertId && !this.hasLoadedAttachments) {
        this.getAttachInfo(this.expertId);
      }
    },
    
    getFileIcon(url) {
      if (!url) return 'el-icon-document';
      const ext = url.toLowerCase();
      if (ext.endsWith('.pdf')) return 'el-icon-document-checked';
      if (ext.endsWith('.png') || ext.endsWith('.jpg') || ext.endsWith('.jpeg')) return 'el-icon-picture';
      return 'el-icon-document';
    },
    
    getFileName(url) {
      if (!url) return '';
      const parts = url.split('/');
      return parts[parts.length - 1];
    },
    
    async previewFile(attachmentType) {
      const fileInfo = this.attachmentFiles[attachmentType];
      if (!fileInfo || !fileInfo.fileId) {
        this.$message.warning('文件未上传');
        return;
      }

      try {
        // 直接使用已经获取到的文件信息
        this.previewUrl = fileInfo.url;
        this.previewFileName = fileInfo.fileName;
        this.previewDialogVisible = true;
      } catch (error) {
        console.error('预览文件失败:', error);
        this.$message.error('预览文件失败');
      }
    },
    
    closePreview() {
      this.previewUrl = '';
      this.previewFileName = '';
      this.previewDialogVisible = false;
    },
    
    deleteFile(attachmentType) {
      this.attachmentFiles[attachmentType] = {
        fileId: null,
        fileName: '未上传文件',
        url: null
      };
      this.formErrors[attachmentType] = '';
    },
    
    // 格式化日期时间
    formatDateTime(datetime) {
      if (!datetime) return '-';
      return datetime.replace(/\..*$/, '').replace('T', ' ');
    },
    
    // 获取附件信息
    async getAttachInfo(expertId) {
      if (!expertId) {
        return;
      }
      
      // 判断是否已加载过该专家附件
      if (this.hasLoadedAttachments && expertId === this.expertId) {
        return;
      }
      
      try {
        const response = await getExpertAttach(expertId);
        
        if (response?.code === 200 && response.data) {
          const attachData = response.data;
          
          // 收集唯一的文件ID
          const fileIdMap = new Map();
          
          // 将所有附件类型和文件ID对应起来
          const attachTypes = {
            idCard: attachData.idCard,
            certificate: attachData.certificate,
            qualification: attachData.qualification, 
            supportMater: attachData.supportMater,
            applicationForm: attachData.applicationForm
          };
          
          // 初始化所有附件类型的默认值
          Object.keys(attachTypes).forEach(type => {
            const fileId = attachTypes[type];
            if (fileId) {
              fileIdMap.set(fileId, type);
              // 先设置临时值，避免界面显示错误
              this.$set(this.attachmentFiles, type, {
                fileId: fileId,
                fileName: '加载中...',
                address: null
              });
            }
          });
          
          // 并行请求所有文件信息
          const uniqueFileIds = Array.from(fileIdMap.keys());
          
          if (uniqueFileIds.length > 0) {
            // 使用Promise.all并行请求
            const fileInfoRequests = uniqueFileIds.map(fileId => {
              return getFileInfo(fileId)
                .then(response => {
                  const fileData = response.code === 200 ? response.data : response;
                  return { fileId, fileData };
                })
                .catch(error => {
                  console.error(`获取文件 ${fileId} 信息失败:`, error);
                  return { fileId, error: true };
                });
            });
            
            // 等待所有请求完成
            const results = await Promise.all(fileInfoRequests);
            
            // 处理结果
            results.forEach(result => {
              const { fileId, fileData, error } = result;
              const attachType = fileIdMap.get(fileId);
              
              if (!error && fileData && fileData.fileId && fileData.address) {
                this.$set(this.attachmentFiles, attachType, {
                  fileId: fileData.fileId,
                  fileName: fileData.fileName || '未知文件名',
                  address: fileData.address
                });
              } else {
                this.$set(this.attachmentFiles, attachType, {
                  fileId: fileId,
                  fileName: '获取文件信息失败',
                  address: null
                });
              }
            });
          }
        }
      } catch (error) {
        console.error('获取附件信息失败:', error);
      } finally {
        // 标记该专家的附件已加载
        this.expertId = expertId;
        this.hasLoadedAttachments = true;
      }
    },

    // 更新附件文件信息
    async updateAttachmentFiles(fileIds) {
      // 创建一个 Set 来存储已经请求过的文件ID
      const requestedFileIds = new Set();
      
      for (const [key, fileId] of Object.entries(fileIds)) {
        if (!fileId || requestedFileIds.has(fileId)) {
          console.log(`${key} 没有文件ID或已经请求过`);
          continue;
        }

        requestedFileIds.add(fileId);

        try {
          console.log(`开始获取 ${key} 的文件信息, fileId:`, fileId);
          const response = await getFileInfo(fileId);
          console.log(`${key} 文件信息响应:`, response);

          if (response?.code === 200 && response.data) {
            const fileData = response.data;
            // 使用 $set 确保响应式更新
            this.$set(this.attachmentFiles, key, {
              fileId: fileData.fileId,
              fileName: fileData.fileName || '未知文件名',
              url: fileData.address,  // 使用address作为文件URL
              address: fileData.address,
              uploadTime: fileData.uploadTime
            });

            // 如果其他附件也使用相同的fileId，直接复用结果
            for (const [otherKey, otherId] of Object.entries(fileIds)) {
              if (otherKey !== key && otherId === fileId) {
                this.$set(this.attachmentFiles, otherKey, {
                  ...this.attachmentFiles[key]
                });
              }
            }
          } else {
            console.warn(`获取 ${key} 文件信息失败:`, response);
            this.$set(this.attachmentFiles, key, {
              fileId: fileId,
              fileName: '获取文件信息失败',
              url: null,
              address: null
            });
          }
        } catch (error) {
          console.error(`获取 ${key} 文件信息失败:`, error);
          this.$set(this.attachmentFiles, key, {
            fileId: fileId,
            fileName: '获取文件信息失败',
            url: null,
            address: null
          });
        }
      }
      
      console.log('所有附件信息更新完成:', this.attachmentFiles);
    },
    
    // 获取附件类型
    getAttachmentType(key) {
      const mapping = {
        'idCardFrontUrl': 'idCard',                    // 身份证
        'idCardBackUrl': 'certificate',                // 最高学历(学位)证书及技术职称
        'degreeCertificateUrl': 'qualification',       // 职业资格
        'professionalCertificateUrl': 'supportMater',  // 证明材料
        'otherDocumentsUrl': 'applicationForm'         // 专家入库申请表
      };
      console.log('获取附件类型:', {
        输入key: key,
        映射结果: mapping[key],
        当前文件信息: this.attachmentFiles[mapping[key]]
      });
      return mapping[key] || key;
    },
    
    // 修改文件上传方法
    async handleFileUpload(attachmentType, event) {
      const file = event.target.files[0];
      if (!file) return;
      
      // 检查文件大小（10MB）
      if (file.size > 10 * 1024 * 1024) {
        this.formErrors[attachmentType] = '文件大小不能超过10MB';
        return;
      }
      
      // 检查文件类型
      const allowedTypes = ['application/pdf', 'image/png', 'image/jpeg'];
      if (!allowedTypes.includes(file.type)) {
        this.formErrors[attachmentType] = '请上传PDF或图片文件';
        return;
      }
      
      this.formErrors[attachmentType] = '';
      
      // TODO: 这里需要实现文件上传到服务器的逻辑
      // 上传成功后更新 attachmentFiles
      try {
        // 模拟上传成功
        this.attachmentFiles[attachmentType] = {
          fileId: 'temp_' + Date.now(),
          fileName: file.name,
          url: URL.createObjectURL(file)
        };
      } catch (error) {
        console.error('文件上传失败:', error);
        this.$message.error('文件上传失败');
      }
    },
    
        // 下载文件
    async downloadFile(attachmentType) {
      try {
        console.log(`开始处理文件下载请求，类型: ${attachmentType}`);
        
        // 获取文件信息
        const fileInfo = this.attachmentFiles[attachmentType];
        console.log(`获取到的文件信息:`, JSON.stringify(fileInfo, null, 2));
        
        if (!fileInfo) {
          throw new Error('文件信息不存在');
        }
        
        if (!fileInfo.fileId) {
          throw new Error('文件未上传');
        }

        // 直接使用当前的文件信息
        const fileUrl = fileInfo.address;
        if (!fileUrl) {
          throw new Error('文件地址无效');
        }

        console.log(`准备下载文件:`, {
          类型: attachmentType,
          文件名: fileInfo.fileName,
          文件ID: fileInfo.fileId,
          下载地址: fileUrl
        });

        // 调用下载接口
        const response = await downloadFile(fileUrl);
        
        // 检查响应类型和内容
        console.log('下载响应:', response);
        
        // 尝试解析响应是否为JSON
        if (response.type.includes('application/json')) {
          // 如果是JSON响应，说明可能是错误信息
          const reader = new FileReader();
          const textContent = await new Promise((resolve) => {
            reader.onload = () => resolve(reader.result);
            reader.readAsText(response);
          });
          
          try {
            const result = JSON.parse(textContent);
            throw new Error(result.message || '下载失败');
          } catch (e) {
            throw new Error('下载失败: ' + (e.message || '未知错误'));
          }
        }
        
        if (response.size === 0) {
          throw new Error('下载的文件内容为空');
        }
        
        // 直接使用响应的Blob对象
        const blob = response;
        
        // 创建下载链接
        const downloadUrl = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.style.display = 'none';
        link.href = downloadUrl;
        link.setAttribute('download', fileInfo.fileName);
        
        // 添加到文档并触发点击
        document.body.appendChild(link);
        link.click();
        
        // 清理
        document.body.removeChild(link);
        window.URL.revokeObjectURL(downloadUrl);
        
        console.log('文件下载成功:', fileInfo.fileName);
        this.$message.success('文件下载成功');
      } catch (error) {
        console.error('下载文件失败:', error);
        this.$message.error(error.message || '下载文件失败，请重试');
      }
    },
  },
  filters: {
    // 日期格式化
    formatDate(value) {
      if (!value) return '';
      return new Date(value).toLocaleDateString('zh-CN');
    }
  }
}
</script>

<style lang='scss' scoped>
.container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
  color: #2c3e50;
}

.content-wrapper {
  flex: 1;
  padding: 24px;
  max-width: 100%;
  margin: 0 auto;
  width: 100%;
}

.status-bar {
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  padding: 20px 24px;
  border-radius: 12px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  display: flex;
  justify-content: space-between;
  align-items: center;
  border: 1px solid rgba(255, 255, 255, 0.8);
}

.current-status {
  font-size: 16px;
  color: #1a1a1a;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
  
  i {
    font-size: 20px;
    color: #1890ff;
  }
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 9999;

  i {
    font-size: 32px;
    color: #1890ff;
    margin-bottom: 16px;
  }

  span {
    font-size: 16px;
    color: #1a1a1a;
  }
}

.form-container {
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 24px;
  overflow: hidden;
}

/* 标签页样式优化 */
.el-tabs {
  .el-tabs__header {
    margin: 0;
    padding: 0 24px;
    background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
    border-bottom: 1px solid #e8e8e8;
  }

  .el-tabs__nav-wrap::after {
    display: none;
  }

  .el-tabs__item {
    height: 56px;
    line-height: 56px;
    font-size: 15px;
    color: #666;
    transition: all 0.3s;

    &:hover {
      color: #1890ff;
    }

    &.is-active {
      color: #1890ff;
      font-weight: 500;
    }
  }

  .el-tabs__active-bar {
    height: 3px;
    border-radius: 3px;
    background: linear-gradient(90deg, #1890ff 0%, #69c0ff 100%);
  }
}

/* 表单区域样式优化 */
.form-section {
  padding: 32px;
  border-bottom: 1px solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }

  .section-header {
    margin-bottom: 28px;
    padding-bottom: 16px;
    border-bottom: 2px solid #f0f0f0;
    position: relative;
    display: flex;
    align-items: center;
    gap: 12px;

    &::after {
      content: '';
      position: absolute;
      bottom: -2px;
      left: 0;
      width: 60px;
      height: 2px;
      background: linear-gradient(90deg, #1890ff 0%, #69c0ff 100%);
    }

    h2 {
      font-size: 18px;
      color: #1a1a1a;
      margin: 0;
      font-weight: 600;
    }

    .section-icon {
      font-size: 20px;
      color: #1890ff;
    }
  }
}

/* 个人信息布局优化 */
.personal-info-container {
  display: grid;
  grid-template-columns: auto 1fr;
  gap: 32px;
  align-items: start;
}

.photo-section {
  width: 200px;
  position: sticky;
  top: 24px;
}

.photo-container {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 16px;
  text-align: center;
  border: 1px solid #e8e8e8;
  transition: all 0.3s;

  &:hover {
    border-color: #1890ff;
    box-shadow: 0 2px 12px rgba(24, 144, 255, 0.1);
  }
}

.photo-preview {
  width: 160px;
  height: 200px;
  margin: 0 auto 16px;
  border-radius: 8px;
  overflow: hidden;
  border: 2px solid #e8e8e8;
  position: relative;

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .photo-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    opacity: 0;
    transition: all 0.3s;
    color: white;

    &:hover {
      opacity: 1;
    }

    i {
      font-size: 24px;
      margin-bottom: 8px;
    }
  }
}

/* 表单字段布局优化 */
.form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
}

.form-group {
  position: relative;

  label {
    display: block;
    font-size: 14px;
    color: #606266;
    margin-bottom: 8px;
    font-weight: 500;

    &.required::after {
      content: '*';
      color: #f56c6c;
      margin-left: 4px;
    }
  }

  .readonly-value {
    padding: 12px 16px;
    background: #f8f9fa;
    border-radius: 8px;
    border: 1px solid #e8e8e8;
    min-height: 40px;
    color: #1a1a1a;
    font-size: 14px;
  }

  .editable-value {
    input,
    select,
    textarea {
      width: 100%;
      padding: 12px 16px;
      border: 1px solid #e8e8e8;
      border-radius: 8px;
      transition: all 0.3s;
      font-size: 14px;
      color: #1a1a1a;
      background: #ffffff;

      &:hover {
        border-color: #1890ff;
      }

      &:focus {
        border-color: #1890ff;
        box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
        outline: none;
      }
    }
  }
}

/* 工作履历表格样式优化 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 24px;

  &::before {
    display: none;
  }

  th {
    background: #f8f9fa !important;
    font-weight: 600;
    color: #1a1a1a;
    padding: 16px !important;
  }

  td {
    padding: 16px !important;
  }
}

/* 附件上传区域样式优化 */
.attachments-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
}

.attachment-item {
  background: #ffffff;
  border-radius: 12px;
  padding: 20px;
  border: 1px solid #e8e8e8;
  transition: all 0.3s;

  &:hover {
    border-color: #1890ff;
    box-shadow: 0 2px 12px rgba(24, 144, 255, 0.1);
  }
}

.attachment-card {
  display: flex;
  align-items: center;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    background: #e6f7ff;
    
    .attachment-action {
      color: #1890ff;
    }
  }

  .attachment-icon {
    font-size: 24px;
    color: #1890ff;
    margin-right: 16px;
  }

  .attachment-info {
    flex: 1;
    
    .attachment-name {
      font-size: 15px;
      color: #333;
      margin-bottom: 6px;
      display: block;
      font-weight: 500;
    }

    .attachment-action {
      font-size: 14px;
      color: #666;
      display: flex;
      align-items: center;
      gap: 4px;
      transition: all 0.3s;

      i {
        font-size: 14px;
      }
    }

    .attachment-actions {
      display: flex;
      gap: 16px;
      margin-top: 8px;

      .action-download, .action-delete {
        display: flex;
        align-items: center;
        gap: 4px;
        font-size: 14px;
        cursor: pointer;
        transition: all 0.3s;

        i {
          font-size: 14px;
        }
      }

      .action-download {
        color: #1890ff;
        
        &:hover {
          color: #40a9ff;
        }
      }

      .action-delete {
        color: #ff4d4f;
        
        &:hover {
          color: #ff7875;
        }
      }
    }
  }
}

.attachment-empty {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 12px;
  color: #999;
  font-size: 14px;

  i {
    font-size: 20px;
  }
}

/* 预览对话框样式优化 */
.preview-dialog {
  .el-dialog__header {
    padding: 20px 24px;
    border-bottom: 1px solid #e8e8e8;
  }

  .el-dialog__body {
    padding: 24px;
  }

  .preview-container {
    background: #f8f9fa;
    border-radius: 8px;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 400px;
  }
}

/* 响应式布局调整 */
@media (max-width: 768px) {
  .content-wrapper {
    padding: 16px;
  }

  .personal-info-container {
    grid-template-columns: 1fr;
  }

  .photo-section {
    width: 100%;
    position: static;
  }

  .form-grid {
    grid-template-columns: 1fr;
  }

  .attachments-container {
    grid-template-columns: 1fr;
  }
}

/* 搜索表单样式优化 */
.search-form {
  background: #ffffff;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 24px;

  .el-form {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 20px;
    align-items: flex-start;

    @media (max-width: 768px) {
      grid-template-columns: 1fr;
    }
  }

  .el-form-item {
    margin-bottom: 0;
    
    &.search-actions {
      display: flex;
      justify-content: flex-end;
      gap: 12px;
      grid-column: 1 / -1;
      margin-top: 8px;
    }
  }

  .el-form-item__label {
    font-size: 14px;
    color: #606266;
    padding-right: 12px;
    line-height: 40px;
    font-weight: 500;
  }

  .el-input__inner,
  .el-select .el-input__inner,
  .el-cascader .el-input__inner {
    height: 40px;
    line-height: 40px;
    border-radius: 8px;
    border: 1px solid #dcdfe6;
    transition: all 0.3s;
    font-size: 14px;
    color: #606266;
    background: #f5f7fa;

    &:hover {
      border-color: #c0c4cc;
    }

    &:focus {
      border-color: #409eff;
      background: #ffffff;
    }
  }

  .el-select,
  .el-cascader {
    width: 100%;
  }

  .el-button {
    height: 40px;
    padding: 0 20px;
    font-size: 14px;
    border-radius: 8px;
    transition: all 0.3s;

    &.el-button--primary {
      background: linear-gradient(135deg, #409eff 0%, #3a8ee6 100%);
      border: none;
      box-shadow: 0 2px 6px rgba(64, 158, 255, 0.2);

      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
      }

      &:active {
        transform: translateY(0);
      }
    }

    &.el-button--default {
      border: 1px solid #dcdfe6;
      color: #606266;
      background: #ffffff;

      &:hover {
        color: #409eff;
        border-color: #c6e2ff;
        background: #ecf5ff;
      }
    }
  }

  .age-range {
    display: flex;
    align-items: center;
    gap: 8px;

    .el-input {
      width: calc(50% - 16px);
    }

    .separator {
      color: #909399;
      font-size: 14px;
    }
  }
}

/* 表格样式优化 */
.el-table {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 24px;

  &::before {
    display: none;
  }

  th {
    background: #f5f7fa !important;
    padding: 16px !important;
    font-weight: 600;
    color: #606266;
    border-bottom: 1px solid #ebeef5;
  }

  td {
    padding: 16px !important;
    color: #606266;
  }

  .el-table__row {
    transition: all 0.3s;

    &:hover > td {
      background-color: #f5f7fa !important;
    }
  }

  .el-button--text {
    padding: 0 8px;
    font-size: 14px;
    
    &:hover {
      color: #409eff;
      background: #ecf5ff;
      border-radius: 4px;
    }
  }
}

/* 标签样式优化 */
.el-tag {
  border-radius: 4px;
  padding: 0 8px;
  height: 24px;
  line-height: 22px;
  font-size: 12px;

  &.el-tag--success {
    background: #f0f9eb;
    border-color: #e1f3d8;
    color: #67c23a;
  }

  &.el-tag--warning {
    background: #fdf6ec;
    border-color: #faecd8;
    color: #e6a23c;
  }

  &.el-tag--danger {
    background: #fef0f0;
    border-color: #fde2e2;
    color: #f56c6c;
  }

  &.el-tag--info {
    background: #f4f4f5;
    border-color: #e9e9eb;
    color: #909399;
  }
}

/* 分页样式优化 */
.el-pagination {
  padding: 24px 0;
  text-align: center;

  .btn-prev,
  .btn-next {
    border-radius: 4px;
    padding: 0 8px;
    min-width: 32px;
  }

  .el-pager li {
    border-radius: 4px;
    min-width: 32px;

    &.active {
      background: #409eff;
      color: #ffffff;
    }

    &:hover {
      color: #409eff;
    }
  }

  .el-pagination__sizes {
    margin-right: 16px;
  }
}

/* 空状态样式优化 */
.empty-tip {
  padding: 48px 0;
  text-align: center;
  background: #ffffff;
  border-radius: 12px;
  margin-bottom: 24px;
  color: #909399;

  i {
    font-size: 48px;
    margin-bottom: 16px;
    color: #dcdfe6;
  }

  span {
    font-size: 14px;
  }
}

/* 加载状态样式优化 */
.loading-overlay {
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(4px);

  .loading-spinner {
    font-size: 32px;
    color: #409eff;
    animation: rotate 1s linear infinite;
  }

  .loading-text {
    margin-top: 16px;
    font-size: 14px;
    color: #606266;
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 工作经历表格样式 */
.form-section {
  #work-experience {
    .el-table {
      margin: 0;
      border-radius: 4px;
      overflow: hidden;

      &::before {
        display: none;
      }

      .el-table__header-wrapper {
        th {
          background-color: #f5f7fa !important;
          color: #606266;
          font-weight: 600;
          padding: 8px 0;
        }
      }

      .el-table__body-wrapper {
        td {
          padding: 8px;
        }
      }

      .work-unit {
        display: inline-block;
        max-width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
}

/* 表格hover效果 */
.el-table__body tr:hover > td {
  background-color: #f5f7fa !important;
}

/* 表格单元格内容垂直居中 */
.el-table td, .el-table th {
  vertical-align: middle;
}

/* 表格边框颜色 */
.el-table--border, .el-table--group {
  border: 1px solid #ebeef5;
}

.el-table td, .el-table th.is-leaf {
  border-bottom: 1px solid #ebeef5;
}

.el-table--border td, .el-table--border th {
  border-right: 1px solid #ebeef5;
}

/* 表格内容字体大小和颜色 */
.el-table {
  font-size: 14px;
  color: #606266;
}

/* 表格头部样式 */
.el-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  padding: 8px 0;
}

/* 表格单元格样式 */
.el-table td {
  padding: 8px;
}

/* 表格hover时的样式 */
.el-table--enable-row-hover .el-table__body tr:hover > td {
  background-color: #f5f7fa;
}

/* 其他信息样式 */
.form-section {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);

  .form-group {
    margin-bottom: 20px;

    label {
      display: block;
      font-size: 14px;
      color: #606266;
      margin-bottom: 10px;
      font-weight: 500;
    }

    .other-info-textarea {
      width: 100%;
      
      ::v-deep .el-textarea__inner {
        padding: 12px;
        font-size: 14px;
        line-height: 1.8;
        color: #606266;
        background-color: #f5f7fa;
        border: 1px solid #e4e7ed;
        border-radius: 4px;

        &:disabled {
          background-color: #f5f7fa;
          border-color: #e4e7ed;
          color: #606266;
          cursor: not-allowed;
        }

        &::placeholder {
          color: #c0c4cc;
        }
      }
    }
  }

  .info-meta {
    margin-top: 16px;
    padding-top: 16px;
    border-top: 1px solid #ebeef5;
    display: flex;
    gap: 24px;
    color: #909399;
    font-size: 13px;

    .meta-item {
      display: flex;
      align-items: center;
      gap: 4px;

      i {
        font-size: 14px;
      }
    }
  }
}

/* 加载状态样式 */
.el-loading-mask {
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 4px;
}

.el-loading-spinner {
  .el-loading-text {
    color: #409eff;
    font-size: 14px;
    margin: 3px 0;
  }

  .circular {
    width: 30px;
    height: 30px;
  }
}
</style>